<?php
/* -------------------------------------------------------------------------------------
* 	ID:						$Id: advanced_search_result.php 291 2013-09-23 10:37:24Z phone.mueller@googlemail.com $
* 	Letzter Stand:			$Revision: 291 $
* 	zuletzt geaendert von:	$Author: siekiera $
* 	Datum:					$Date: 2013-09-23 10:37:24 +0000 (Mon, 23 Sep 2013) $
*
* 	SEO:mercari by Siekiera Media
* 	http://www.seo-mercari.de
*
* 	Copyright (c) since 2011 SEO:mercari
* --------------------------------------------------------------------------------------
* 	based on:
* 	(c) 2000-2001 The Exchange Project  (earlier name of osCommerce)
* 	(c) 2002-2003 osCommerce - www.oscommerce.com
* 	(c) 2003     nextcommerce - www.nextcommerce.org
* 	(c) 2005     xt:Commerce - www.xt-commerce.com
*
* 	Released under the GNU General Public License
* ----------------------------------------------------------------------------------- */
include('includes/application_top.php');

$error = 0;

$_GET['keywords'] = urlencode(preg_replace('/[^a-zA-Z0-9-]/u', ' ', trim($_GET['keywords'])));
if(MODULE_SEO_URL_INDEX_STATUS == 'True') {
	if(isset($_GET['box']) && !empty($_GET['keywords']))
		redirect(href_link('keywords/'.$_GET['keywords'].'/'));
}
if(empty($_GET['keywords']))
	redirect(href_link(FILENAME_ADVANCED_SEARCH));

$_SESSION['keyword'] = urldecode($_GET['keywords']);
$_GET['keywords'] = urldecode($_GET['keywords']);

$module_smarty = new Smarty();

require(DIR_FS_CATALOG.'templates/'.CURRENT_TEMPLATE.'/source/boxes.php');

require_once(DIR_FS_INC.'inc.parse_search_string.php');
require_once(DIR_FS_INC.'inc.get_subcategories.php');
require_once(DIR_FS_INC.'inc.get_currencies_values.php');

$errorno = 0;
$keyerror = 0;

if(isset($_GET['keywords']) && empty($_GET['keywords']))
	$keyerror = 1;

if ((isset($_GET['keywords']) && empty($_GET['keywords'])) && (isset($_GET['pfrom']) && empty($_GET['pfrom'])) && (isset($_GET['pto']) && empty($_GET['pto']))) {
	$errorno += 1;
	$error = 1;
}
elseif (isset($_GET['keywords']) && empty($_GET['keywords']) && !(isset($_GET['pfrom'])) && !(isset($_GET['pto']))) {
	$errorno += 1;
	$error = 1;
}

if (strlen($_GET['keywords']) < 3 && strlen($_GET['keywords']) > 0 && $error == 0) {
	$errorno += 1;
	$error = 1;
	$keyerror = 1;
}

if (strlen($_GET['pfrom']) > 0) {
	$pfrom_to_check = $db->db_prepare($_GET['pfrom']);
	if (!settype($pfrom_to_check, "double")) {
		$errorno += 10000;
		$error = 1;
	}
}

if (strlen($_GET['pto']) > 0) {
	$pto_to_check = $_GET['pto'];
	if (!settype($pto_to_check, "double")) {
		$errorno += 100000;
		$error = 1;
	}
}

if (strlen($_GET['pfrom']) > 0 && !(($errorno & 10000) == 10000) && strlen($_GET['pto']) > 0 && !(($errorno & 100000) == 100000)) {
	if ($pfrom_to_check > $pto_to_check) {
		$errorno += 1000000;
		$error = 1;
	}
}

if (strlen($_GET['keywords']) > 0) {
	if (!parse_search_string(stripslashes($_GET['keywords']), $search_keywords)) {
		$errorno += 10000000;
		$error = 1;
		$keyerror = 1;
	}
}

if ($error == 1 && $keyerror != 1)
	redirect(href_link(FILENAME_ADVANCED_SEARCH, 'errorno='.$errorno.'&'.get_all_get_params(array ('x', 'y'))));
else {

	/*
	 *    search process starts here
	 */
	
	include(DIR_WS_MODULES.'product_filter.php');
	
	$breadcrumb->add(NAVBAR_TITLE1_ADVANCED_SEARCH, href_link(FILENAME_ADVANCED_SEARCH));
	$breadcrumb->add(NAVBAR_TITLE2_ADVANCED_SEARCH, href_link(FILENAME_ADVANCED_SEARCH_RESULT, 'keywords='.htmlspecialchars($_GET['keywords']).'&search_in_description='.$_GET['search_in_description'].'&categories_id='.(int)$_GET['categories_id'].'&inc_subcat='.$_GET['inc_subcat'].'&brand_id='.(int)$_GET['brand'].'&pfrom='.$_GET['pfrom'].'&pto='.$_GET['pto'].'&dfrom='.$_GET['dfrom'].'&dto='.$_GET['dto']));
	
	if ($_SESSION['customers_status']['customers_fsk18_display'] == '0')
		$fsk_lock = " AND p.products_fsk18 != '1' ";
	else
		unset ($fsk_lock);
	
	//group check
	if (GROUP_CHECK == 'true')
		$group_check = " AND p.group_permission_".$_SESSION['customers_status']['customers_status_id']."=1 ";
	else
		unset ($group_check);

	//brand if set
	if (isset($_GET['brand']) && not_null($_GET['brand']))
		$manu_check = " AND p.brand_id = '".(int)$_GET['brand']."' ";

	//include subcategories if needed
	if (isset($_GET['categories_id']) && not_null($_GET['categories_id'])) {
		if ($_GET['inc_subcat'] == '1') {
			$subcategories_array = array ();
			get_subcategories($subcategories_array, (int)$_GET['categories_id']);
			$subcat_join = " LEFT OUTER JOIN ".TABLE_PRODUCTS_TO_CATEGORIES." AS p2c ON (p.products_id = p2c.products_id) ";
			$subcat_where = " AND p2c.categories_id IN ('".(int) $_GET['categories_id']."' ";
			foreach ($subcategories_array AS $scat)
				$subcat_where .= ", '".$scat."'";

			$subcat_where .= ") ";
		} else {
			$subcat_join = " LEFT OUTER JOIN ".TABLE_PRODUCTS_TO_CATEGORIES." AS p2c ON (p.products_id = p2c.products_id) ";
			$subcat_where = " AND p2c.categories_id = '".(int) $_GET['categories_id']."' ";
		}
	}

	if ($_GET['pfrom'] || $_GET['pto']) {
		$rate = get_currencies_values($_SESSION['currency']);
		$rate = $rate['value'];
		if ($rate && $_GET['pfrom'] != '')
			$pfrom = $_GET['pfrom'] / $rate;
		if ($rate && $_GET['pto'] != '')
			$pto = $_GET['pto'] / $rate;
	}

	//price filters
	if (($pfrom != '') && (is_numeric($pfrom)))
		$pfrom_check = " AND (IF(s.status = '1' AND p.products_id = s.products_id, s.specials_price_".$_SESSION['customers_status']['customers_status_id'].", p.products_price) >= ".$pfrom.") ";
	else
		unset ($pfrom_check);

	if (($pto != '') && (is_numeric($pto)))
		$pto_check = " AND (IF(s.status = '1' AND p.products_id = s.products_id, s.specials_price_".$_SESSION['customers_status']['customers_status_id'].", p.products_price) <= ".$pto." ) ";
	else
		unset ($pto_check);

	//build query
	$select_str = "SELECT
	                  p.products_id,
	                  p.products_price,
	                  p.products_model,
	                  p.products_ean,
	                  p.products_isbn,
	                  p.products_quantity,
	                  p.products_shippingtime,
	                  p.products_fsk18,
	                  p.products_image,
	                  p.products_weight,
	                  p.products_tax_class_id,
					  p.products_vpe,
					  p.products_vpe_status,
					  p.products_vpe_value,
	                  pd.products_name,
	                  pd.products_short_description,
	                  pd.products_description
					  ";

	$from_str  = " FROM 
						".TABLE_PRODUCTS." AS p
					LEFT JOIN 
						".TABLE_PRODUCTS_DESCRIPTION." AS pd ON (p.products_id = pd.products_id)
					LEFT JOIN 
						".TABLE_PRODUCTS_TO_CATEGORIES." AS pc ON (p.products_id = pc.products_id)
					LEFT JOIN 
						".TABLE_CATEGORIES." AS c ON (pc.categories_id = c.categories_id)";
	$from_str .= $subcat_join;
	if (SEARCH_IN_ATTR == 'true') { 
		$from_str .= " LEFT OUTER JOIN ".TABLE_PRODUCTS_ATTRIBUTES." AS pa ON (p.products_id = pa.products_id) 
						LEFT OUTER JOIN ".TABLE_PRODUCTS_OPTIONS_VALUES." AS pov ON (pa.options_values_id = pov.products_options_values_id) "; }
	$from_str .= "LEFT OUTER JOIN ".TABLE_SPECIALS." AS s ON (p.products_id = s.products_id) AND s.status = '1'";

	if ((DISPLAY_PRICE_WITH_TAX == 'true') && ((isset($_GET['pfrom']) && not_null($_GET['pfrom'])) || (isset($_GET['pto']) && not_null($_GET['pto'])))) {
		if (!isset($_SESSION['customer_country_id'])) {
			$_SESSION['customer_country_id'] = STORE_COUNTRY;
			$_SESSION['customer_zone_id'] = STORE_ZONE;
		}
		$from_str .= " LEFT OUTER JOIN ".TABLE_TAX_RATES." tr ON (p.products_tax_class_id = tr.tax_class_id) 
						LEFT OUTER JOIN ".TABLE_ZONES_TO_GEO_ZONES." gz ON (tr.tax_zone_id = gz.geo_zone_id) ";
		$tax_where = " AND (gz.zone_country_id IS NULL OR gz.zone_country_id = '0' OR gz.zone_country_id = '".(int) $_SESSION['customer_country_id']."') AND (gz.zone_id is null OR gz.zone_id = '0' OR gz.zone_id = '".(int) $_SESSION['customer_zone_id']."')";
	} else
		unset ($tax_where);

	//where-string
	$where_str = " WHERE 
						p.products_status = '1' 
					AND 
						c.categories_status = '1' 
					AND 
						pd.language_id = '".(int) $_SESSION['languages_id']."'".$subcat_where.$filter_products.$fsk_lock.$manu_check.$group_check.$tax_where.$pfrom_check.$pto_check;

	//go for keywords... this is the main search process
	if (isset($_GET['keywords']) && not_null($_GET['keywords'])) {
		if (parse_search_string(stripslashes($_GET['keywords']), $search_keywords)) {
			$where_str .= " AND ( ";
			for ($i = 0, $n = sizeof($search_keywords); $i < $n; $i ++) {
				switch ($search_keywords[$i]) {
					case '(' :
					case ')' :
					case 'and' :
					case 'or' :
						$where_str .= " ".$search_keywords[$i]." ";
						break;
					default :
						$where_str .= " ( ";
						$where_str .= "pd.products_keywords LIKE ('%".addslashes($search_keywords[$i])."%') ";
						if (SEARCH_IN_DESC == 'true') {
						   $where_str .= "OR pd.products_description LIKE ('%".addslashes($search_keywords[$i])."%') ";
						   $where_str .= "OR pd.products_short_description LIKE ('%".addslashes($search_keywords[$i])."%') ";
						}
						$where_str .= "OR pd.products_name LIKE ('%".addslashes($search_keywords[$i])."%') ";
						$where_str .= "OR p.products_model LIKE ('%".addslashes($search_keywords[$i])."%') ";
						if (SEARCH_IN_ATTR == 'true') {
						   $where_str .= "OR (pov.products_options_values_name LIKE ('%".addslashes($search_keywords[$i])."%') ";
						   $where_str .= "AND pov.language_id = '".(int) $_SESSION['languages_id']."')";
						}
						$where_str .= " ) ";
						break;
				}
			}
			$where_str .= " ) ";
		}
	}

	switch ($_GET['multisort']){
		case 'new_asc':
			$order_str = 'GROUP BY p.products_id ORDER BY p.products_date_added ASC';
			break;

		case 'new_desc':
			$order_str = 'GROUP BY p.products_id ORDER BY p.products_date_added DESC';
			break;

		case 'name_asc':
			$order_str = 'GROUP BY p.products_id ORDER BY pd.products_name ASC';
			break;

		case 'name_desc':
			$order_str = 'GROUP BY p.products_id ORDER BY pd.products_name DESC';
			break;

		case 'price_asc':
			$order_str = 'GROUP BY p.products_id ORDER BY p.products_price ASC';
			break;

		case 'specialprice':
			$order_str = 'GROUP BY p.products_id ORDER BY s.specials_price_'.$_SESSION['customers_status']['customers_status_id'].' DESC';
			break;

		case 'price_desc':
			$order_str = 'GROUP BY p.products_id ORDER BY p.products_price DESC';
			break;

		default:
			$order_str = ' GROUP BY p.products_id ORDER BY pd.products_name';
	}

	if(!empty($_GET['keywords']) && $keyerror !=1) {
	
		$listing_sql = $select_str.$from_str.$where_str.$order_str;
		$listing = new page_break($listing_sql, $_GET['page'], true, 'advanced_search_result.php', 'advanced_search');

		if($listing->result) {			
			$rows = 0;
			while(!$listing->sql_string->EOF) { $rows++;
				if($listing->listName == 'mosaic' && empty($listing->sql_string->fields['products_image'])) {}
				else $module_content[] = $product->buildDataArray($listing->sql_string->fields, 'thumbnail', $listing->listData, $rows);
				$listing->sql_string->MoveNext();
			}
			$hits = $listing->sql_string->_numOfRows;
			$module_smarty->assign('KEYWORDS', sprintf(SEARCH_RESULTS_WORDS, $_GET['keywords'], $listing->raw_sql->_numOfRows));
			$module_smarty->assign('language', $_SESSION['language']);
			
			$module_smarty->assign('NAVIGATION', $listing->getLinks());
			$module_smarty->assign('module_content', $module_content);
			$module_smarty->assign('language', $_SESSION['language']);

			$module_smarty->assign('LIST_NAME', $listing->page_name);
			$module_smarty->assign('CLASS_NAME', $listing->listName);
			
			include(DIR_WS_MODULES.'page_view_as.php');
			include(DIR_WS_MODULES.'page_per_site.php');
			include(DIR_WS_MODULES.'page_mulit_sort.php');
			
			$module_smarty->caching = false;
			$module = $module_smarty->fetch(CURRENT_TEMPLATE.'/module/'.$listing->listData['list_file'].'.html');
			
		} else {
			$_SESSION['error_msg'] = urlencode(TEXT_PRODUCT_NOT_FOUND);
			redirect(href_link(FILENAME_ADVANCED_SEARCH));
			include (DIR_WS_MODULES.FILENAME_ERROR_HANDLER);
		}
		
	} else {
		$error = TEXT_PRODUCT_NOT_FOUND;
		include (DIR_WS_MODULES.FILENAME_ERROR_HANDLER);
	}
	
	require_once(DIR_WS_INCLUDES.'xajax/xajax_core/xajax.inc.php');
	include(DIR_WS_INCLUDES.'xajax/xajax.add_cart.php');
	require(DIR_WS_INCLUDES.'header.php');
	
	$hits = $listing->sql_string->_numOfRows;

	if(LOG_SEARCH_RESULTS =='true') {
		if($_SESSION['last_keyword'] != $_SESSION['keyword']) {	
			$_SESSION['last_keyword'] = $_SESSION['keyword'];
			
			$db->db_query("INSERT INTO ".TABLE_SEARCH_QUERIES_ALL." (
								search_text, 
								search_result
							)VALUES(
								".$db->db_prepare($_SESSION['keyword']).",
								'".$hits."')");
		}
	}
}
$smarty->assign('language', $_SESSION['language']);
$smarty->assign('main_content', $module);
$smarty->caching = false;
if (!defined('RM'))
	$smarty->loadFilter('output', 'note');
$smarty->loadFilter('output','trimwhitespace');
$smarty->display(CURRENT_TEMPLATE.'/index.html');
include ('includes/application_bottom.php');